import {  getToken, getUser } from '@/utils/authority';
import { SettingDrawer } from '@ant-design/pro-components';
import { history } from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import { GetUserRoutes } from './services';
import { HomeOutlined } from '@ant-design/icons';
import logo from './assets/icon.png';
import fixMenuItemIcon from './components/FixIcon/FixMenuItemIcon';
import { AvatarDropdown, AvatarName } from './components/RightContent/AvatarDropdown';
import ExtendApp from './components/RightContent/ExtendApp';
import config from './config';

const loginPath = '/user/login';
/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */

export async function getInitialState() {
  const fetchUserInfo = () => {
    try {
      const currentUser = getUser();
      return currentUser.userName ? currentUser : undefined;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  }; // 如果是登录页面，不执行

  if (history.location.pathname.indexOf(loginPath) === -1) {
    const currentUser = fetchUserInfo();
    const token = getToken();
    // 未登录
    if (!token) {
      history.push(loginPath);
    }
    // // SignalR
    // const connectionHub = await fetchSignalRConnection(token, currentTenant.id);

    return {
      fetchUserInfo,
      currentUser: {
        ...currentUser,
      },
      settings: defaultSettings,
      getToken,
      token,
      masterConfig: config
    };
  }

  return {
    fetchUserInfo,
    settings: defaultSettings,
    masterConfig: config,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout = ({ initialState, setInitialState }) => {

  return {
    bgLayoutImgList: [
      {
        src: '/bbg1.png',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: '/bbg2.png',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: '/bbg3.png',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    actionsRender: () => [<ExtendApp key="extendapp" />],
    avatarProps: {
      src: initialState?.currentUser?.avatar,
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
      },
    },
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    logo: initialState?.app?.logo ? `${config.cdnAddress}/${initialState?.app?.logo}` : logo,
    title: initialState?.app?.appName ? initialState?.app?.appName : '用心运维',
    menu: {
      locale: false,
      params: {
        tenantId: initialState?.app?.tenantId,
      },
      request: async (params) => {
        // // initialState.currentUser 中包含了所有用户信息
        const response = await GetUserRoutes({ ...params });
        const transMenu = fixMenuItemIcon(response.data);
        return [ ...transMenu];
      },
    },
    // footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },

    links: [],
    breadcrumbRender: (routers = []) => {
      const breadRouters = routers.map((c) => {
        return { title: c.breadcrumbName, name: c.breadcrumbName, to: c.path ?? c.linkPath };
      });
      return [
        {
          to: '/',
          title: <HomeOutlined />,
          name: <HomeOutlined />,
        },
        ...breadRouters,
      ];
    },
    breadcrumbProps: {
      itemRender: (route) => {
        return (
          <a
            onClick={() => {
              history.replace(route.to);
            }}
          >
            {route.title}
          </a>
        );
      },
    },

    childrenRender: (children) => {
      return (
        <>
          {children}
          <div style={{ display: "none" }}> <SettingDrawer
            disableUrlParams
            enableDarkTheme
            settings={initialState?.settings}
            onSettingChange={(settings) => {
              setInitialState((preInitialState) => ({
                ...preInitialState,
                settings,
              }));
            }}
          />
          </div>
        </>
      );
    },
    ...initialState?.settings,
  };
};
